import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from "/@/utils/authFunction";
import { ElMessage } from 'element-plus';
import { h } from 'vue';

interface Props {
    supplier_id?: string;
}

export default function ({ crudExpose, props }: { crudExpose: CrudExpose, props?: Props }): CreateCrudOptionsRet {
    const pageRequest = async (query: any) => {
        // 如果有supplier_id，则添加到查询参数中
        const params = props?.supplier_id ? { ...query, supplier_id: props.supplier_id } : query;
        return await api.GetList(params);
    };
    const editRequest = async ({ form, row }: EditReq) => {
        if (row.id) {
            form.id = row.id;
        }
        return await api.UpdateObj(form);
    };
    const delRequest = async ({ row }: DelReq) => {
        return await api.DelObj(row.id);
    };
    const addRequest = async ({ form }: AddReq) => {
        // 如果在供应商详情页中添加产品，自动添加供应商ID
        if (props?.supplier_id) {
            form.supplier = props.supplier_id;
        }
        return await api.AddObj(form);
    };

    const exportRequest = async (query: UserPageQuery) => {
        const params = props?.supplier_id ? { ...query, supplier_id: props.supplier_id } : query;
        return await api.exportData(params);
    };

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    export: {
                        show: auth('SupplierProduct:Export'),
                        text: "导出",
                        title: "导出",
                        click() {
                            return exportRequest(crudExpose.getSearchFormData());
                        }
                    },
                    add: {
                        show: auth('SupplierProduct:Create'),
                    },
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 200,
                buttons: {
                    view: {
                        type: 'text',
                        order: 1,
                        show: auth('SupplierProduct:Retrieve')
                    },
                    edit: {
                        type: 'text',
                        order: 2,
                        show: auth('SupplierProduct:Update')
                    },
                    copy: {
                        type: 'text',
                        order: 3,
                        show: auth('SupplierProduct:Copy')
                    },
                    remove: {
                        type: 'text',
                        order: 4,
                        show: auth('SupplierProduct:Delete')
                    },
                },
            },
            columns: {
                supplier: {
                    title: '供应商',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        url: '/api/supplier/',
                        value: 'id',
                        label: 'name',
                        immediate: true
                    }),
                    column: {
                        minWidth: 150,
                    },
                    form: {
                        // 在供应商详情页中添加产品时，不显示供应商选择框
                        show: !props?.supplier_id,
                        rules: [{ required: true, message: '供应商必选' }],
                        component: {
                            placeholder: '请选择供应商',
                            filterable: true,
                            clearable: true,
                        },
                    },
                },
                product_name: {
                    title: '产品名称',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 120,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '产品名称必填' }],
                        component: {
                            placeholder: '请输入产品名称',
                        },
                    },
                },
                product_code: {
                    title: '产品编码',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 100,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '产品编码必填' }],
                        component: {
                            placeholder: '请输入产品编码',
                        },
                    },
                },
                category: {
                    title: '产品类别',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 100,
                    },
                    form: {
                        component: {
                            placeholder: '请输入产品类别',
                        },
                    },
                },
                specification: {
                    title: '规格型号',
                    type: 'input',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                    },
                    form: {
                        component: {
                            placeholder: '请输入规格型号',
                        },
                    },
                },
                unit: {
                    title: '计量单位',
                    type: 'input',
                    search: { show: false },
                    column: {
                        minWidth: 80,
                    },
                    form: {
                        rules: [{ required: true, message: '计量单位必填' }],
                        component: {
                            placeholder: '请输入计量单位',
                        },
                    },
                },
                price: {
                    title: '价格',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 100,
                        sortable: 'custom',
                        formatter: ({ value }: { value: any }) => {
                            if (value === null || value === undefined || value === '') {
                                return '';
                            }
                            try {
                                const numValue = parseFloat(value);
                                return !isNaN(numValue) ? `¥${numValue.toFixed(2)}` : '';
                            } catch (e) {
                                console.error('Price formatting error:', e);
                                return value; // 返回原始值
                            }
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '价格必填' }],
                        component: {
                            placeholder: '请输入价格',
                            min: 0,
                            precision: 2,
                            controlsPosition: 'right',
                        },
                    },
                },
                min_order_quantity: {
                    title: '最小订购量',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 100,
                    },
                    form: {
                        value: 1,
                        component: {
                            placeholder: '请输入最小订购量',
                            min: 1,
                            precision: 0,
                            controlsPosition: 'right',
                        },
                    },
                },
                lead_time: {
                    title: '供货周期(天)',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                    },
                    form: {
                        component: {
                            placeholder: '请输入供货周期(天)',
                            min: 1,
                            precision: 0,
                            controlsPosition: 'right',
                        },
                    },
                },
                quality_standard: {
                    title: '质量标准',
                    type: 'input',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                    },
                    form: {
                        component: {
                            placeholder: '请输入质量标准',
                        },
                    },
                },
                is_active: {
                    title: '是否有效',
                    type: 'dict-switch',
                    search: { show: true },
                    dict: dict({
                        data: [
                            { value: true, label: '有效' },
                            { value: false, label: '无效' }
                        ]
                    }),
                    column: {
                        minWidth: 80,
                        component: {
                            name: 'el-switch',
                            activeText: '',
                            inactiveText: '',
                            inlinePrompt: true,
                            activeValue: true,
                            inactiveValue: false,
                            onChange: async (value: boolean, row: any) => {
                                if (!row || !row.id) {
                                    console.error('无效的行数据');
                                    crudExpose.doRefresh();
                                    return;
                                }
                                try {
                                    const updateData = {
                                        id: row.id,
                                        is_active: value
                                    };
                                    await api.UpdateObj(updateData);
                                } catch (e) {
                                    console.error('更新状态失败:', e);
                                    crudExpose.doRefresh();
                                }
                            }
                        }
                    },
                    form: {
                        value: true,
                        component: {
                            name: 'el-switch',
                            activeText: '',
                            inactiveText: '',
                            inlinePrompt: true,
                            activeValue: true,
                            inactiveValue: false
                        }
                    }
                },
                description: {
                    title: '产品描述',
                    type: 'textarea',
                    search: { show: false },
                    column: {
                        minWidth: 180,
                        showOverflowTooltip: true
                    },
                    form: {
                        component: {
                            placeholder: '请输入产品描述',
                            rows: 3,
                            span: 24
                        },
                    },
                },
                remarks: {
                    title: '备注',
                    type: 'textarea',
                    search: { show: false },
                    column: {
                        minWidth: 150,
                    },
                    form: {
                        component: {
                            placeholder: '请输入备注信息',
                            rows: 3,
                            span: 24
                        },
                    },
                },
            },
        },
    };
} 